<template>
	<view class="main">
		<view class="search-panel">
			<uni-search-bar
				v-model="searchValue"
				class="search-input"
				radius="5"
				:focus="true"
				placeholder="请输入关键字"
				clearButton="auto"
				cancelButton="none"
				@confirm="handleSearch"
			/>
			<button class="search-btn" @tap="handleSearch">搜索</button>
		</view>
		<view class="search-history-panel" v-if="!searched">
			<view class="search-title">搜索记录</view>
			<scroll-view scroll-y="true" style="height: 500rpx; margin-bottom: 100rpx">
				<view class="bnt-list" v-if="!historyList?.length == 0">
					<view class="btn-item" @tap="handleClickItem(item)" v-for="(item, index) in historyList" :key="index">{{ item }}</view>
				</view>
				<uv-empty v-else mode="search" text="暂无搜索记录"></uv-empty>
			</scroll-view>
			<view v-if="historyList?.length > 0">
				<button @tap="handleClear" type="primary" style="background-color: rgba(67, 207, 124, 1)">清空搜索记录</button>
			</view>
		</view>
		<view class="search-list" v-else>
			<view v-if="searchList?.length > 0" style="height: 100%; background: rgba(229, 229, 229, 0.3);padding-top:20rpx;">
				<armed-card v-for="(item, index) in searchList" :key="index" :data="item"></armed-card>
				<view style="height: 100rpx; width: 100%"></view>
			</view>
			<uv-empty v-else mode="list"></uv-empty>
		</view>
	</view>
</template>

<script setup>
import { onLoad, onBackPress } from '@dcloudio/uni-app';
import { ref } from 'vue';
import SearchAPI from '@/api/search/api.ts';
const searched = ref(false);
const searchKey = ref('search_history');
const searchValue = ref('');
const historyList = ref([]);
const searchList = ref([]);
onLoad(() => {
	try {
		const storedLists = uni.getStorageSync(searchKey.value);
		// 确保 storedLists 是数组，如果不是则将其转换为数组或设置为空数组
		historyList.value = Array.isArray(storedLists) ? storedLists : [];
	} catch (error) {
		console.error('Error fetching history:', error);
		historyList.value = []; // 使用空数组作为回退
	}
});

const handleSearch = () => {
	// 确保搜索内容不是空的
	if (searchValue.value) {
		// 调用之前确保historyList.value是数组
		if (!Array.isArray(historyList.value)) {
			historyList.value = [];
		}
		// 检查 searchValue.value 是否已经在 historyList.value 中
		const index = historyList.value.findIndex((item) => item === searchValue.value);
		if (index !== -1) {
			// 如果在列表中，先移除它
			const itemToRemove = historyList.value.splice(index, 1)[0];
			// 然后将它放在最前面
			historyList.value.unshift(itemToRemove);
		} else {
			// 如果不在列表中，直接添加到最前面
			historyList.value.unshift(searchValue.value);
		}
		// 限制列表长度（可选）
		if (historyList.value.length > 10) {
			// 例如，限制为10个历史项
			historyList.value.pop();
		}
	}
	uni.setStorageSync(searchKey.value, historyList.value); //把内容存储到本地
	// 查询列表
	queryList();
};

function queryList() {
	//查询列表接口调用
	SearchAPI.search({ keywords: searchValue.value })
		.then(({ data }) => {
			searchList.value = data;
			searched.value = true;
		})
		.catch(() => {
			searched.value = false;
		});
}

// 点击清除历史搜索记录
const handleClear = () => {
	uni.removeStorageSync(searchKey.value); //清除本地记录
	historyList.value = []; // 直接将 list.value 设置为空数组
};

// 点击历史记录可以直接搜索
const handleClickItem = (it) => {
	searchValue.value = it;
	queryList();
};

//如果有搜索结果 返回时刷新当前页面
onBackPress(() => {
	if (searched.value) {
		uni.redirectTo({ url: '/pages/search/index' });
		return true;
	}
});
</script>

<style scoped lang="scss">
.main {
	height: 100%;
	width: 100%;
	background: #fff;
	display: flex;
	flex-direction: column;
}
.search-panel {
	display: flex;
	height: 100rpx;
	background: #fff;
	align-items: center;
	padding-right: 20rpx;
	.search-input {
		flex: 1;
	}
	.search-btn {
		height: 75rpx;
		line-height: 75rpx;
		font-size: 30.77rpx;
		font-weight: 400;
		letter-spacing: 0px;
	}
	:deep(.uni-searchbar__box) {
		height: 75rpx;
	}
}
.search-history-panel {
	flex: 1;
	height: 0;
	padding: 20rpx;
	.search-title {
		font-size: 30.77rpx;
		font-weight: 400;
		letter-spacing: 0rpx;
		line-height: 42.21rpx;
		color: rgba(0, 0, 0, 1);
		margin-bottom: 10rpx;
	}
	.bnt-list {
		display: flex;
		flex-wrap: wrap;
		.btn-item {
			border: 1px solid rgba(229, 229, 229, 1);
			padding: 12rpx 21rpx;
			font-size: 30.77rpx;
			font-weight: 400;
			letter-spacing: 0rpx;
			line-height: 42.21rpx;
			color: rgba(0, 0, 0, 1);
			margin-right: 40rpx;
			margin-top: 19rpx;
			max-width: 250rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}
}
.search-list {
	flex: 1;
	overflow-y: auto;
	padding: 20rpx;
	height: 0;
	background: #fff;
}
</style>
